import React, { Fragment } from 'react'
import {
  Form, Button, Table, Empty, Pagination, Spin, Col, Row, DatePicker,
  Modal, Input, Select, message, Divider, Tag,
} from 'antd'
import moment from 'moment'
import _ from 'lodash'
import FileSaver from 'file-saver'

import { address } from '@/Utils/apiConfig'
import request from '@/Utils/fecth'
import CheckItem from '../Role/components/CheckItem'
import { checkPermission } from '@/components/AuthComponent/utils'
import { list2Tree } from '@/pages/Dashboard/components/Inner/utils/treeUtils'

import './index.less'

const Option = Select.Option
const checkApi = address.check
const resource = address.resource

export default class CheckList extends React.Component {
  columns = [
    {
      title: '提交人',
      dataIndex: 'applicant_name',
      render: (v) => v || '--',
    },
    {
      title: '类型',
      dataIndex: 'type',
      render: (v) => v || '--',
    },
    {
      title: '被操作对象',
      dataIndex: 'item',
      render: (v) => v || '--',
    },
    {
      title: '审核人',
      dataIndex: 'auditor_name',
      render: (v) => v || '--',
    },
    {
      title: '状态',
      dataIndex: 'status',
      render: (v) => {
        const item = CheckStatus.find(item => item.value === v) || {}
        return <Tag color={item.color}>{item.label || '--'}</Tag>
      },
    },
    {
      title: '提交时间',
      dataIndex: 'createtime',
      render: (v) => v ? moment(v).format('YYYY-MM-DD HH:mm:ss') : '--',
      sorter: true,
    },
    {
      title: '操作',
      dataIndex: 'operation',
      fixed: 'right',
      render: (text, record, index) => (
        <div className="action" id={`popver${index}`} style={{ position: 'relative' }}>
          {
            checkPermission('user-audit-check', 'PUT') &&
            record.status === 'PENDING_REVIEW' &&
            <span className={`common-operation`} onClick={() => this.onOpenModal(record, 'check')}>审核</span>
          }
          {
            checkPermission('user-audit-detail', 'GET') &&
            <span className={`common-operation`} onClick={() => this.onOpenModal(record, 'detail')}>查看</span>
          }
        </div>
      ),
    },
  ]

  constructor(props) {
    super(props)
    this.state = {
      loading: false,
      list: [],
      total: 0,
      modalLoading: false,
      visible: false,
    }
    this.handleRecord = {}
    this.searchOption = {
      pageNum: 1,
      pageSize: 10,
    }
    this.flag = 'check' // 审核：check/查看 detail
    this.type = 'role' // 角色：role/账户 account
  }

  componentDidMount() {
    this.getList()
    this.getResourceList()
  }

  getList = async(values = {}) => {
    this.setState({
      loading: true,
    })
    this.searchOption = {
      ...this.searchOption,
      ...values,
    }
    const { status, data = {}} = await request().get(checkApi.getList, {
      params: {
        ...this.searchOption,
      },
    })
    this.setState({
      loading: false,
    })
    if (status === 200) {
      this.setState({
        list: (data.data || []).map((v, i) => {
          return {
            ...v,
          }
        }),
        total: data.total || 0,
      })
    }
  }

  search = (values) => {
    const { time, type = '', status = '', name = '' } = values || {}
    const [timeStart, timeEnd] = time || []
    if (timeStart && timeEnd) {
      this.searchOption.timeStart = parseInt((moment(timeStart).valueOf()))
      this.searchOption.timeEnd = parseInt((moment(timeEnd).valueOf()))
    } else {
      this.searchOption.timeStart = ''
      this.searchOption.timeEnd = ''
    }
    this.searchOption.searchKey = name
    this.searchOption.type = type
    this.searchOption.status = status
    this.searchOption.pageNum = 1
    this.getList()
  }

  /**
   * 重置
   */
  cancelSearch = () => {
    this.searchForm.resetFields()
    this.searchForm.submit()
  }

  onPageChange = (current, pageSize) => {
    const { searchOption } = this
    searchOption.pageNum = current
    searchOption.pageSize = pageSize
    this.getList()
  };

  onTableChange = (pagination, filters, sorter) => {
    const { order = '' } = sorter || {}
    this.searchOption.orderBy = order === 'ascend' ? 'createTime,asc' : order === 'descend' ? 'createTime,desc' : ''
    this.searchForm.submit()
  }

  /**
   * 获取所有权限
   */
  getResourceList = async() => {
    const { status, data = {}} = await request().get(resource.getList)
    if (status === 200) {
      this.resourceList = (data.data || []).map(v => {
        return {
          id: v.id,
          name: v.name,
          checked: false,
          parentId: v.parent_id,
        }
      })
    }
  }

  /**
   * 审核/查看
   */
  onOpenModal = async(record, flag) => {
    this.handleRecord = record
    this.type = ''
    if ((record.type || '').includes('角色')) {
      this.type = 'role'
    } else if ((record.type || '').includes('账户')) {
      this.type = 'account'
    } else if ((record.type || '').includes('链码')) {
      this.type = 'chaincode'
    }
    this.flag = flag
    const { status, data = {}} = await request().get(checkApi.detail.format({ id: record.id }))
    if (status === 200) {
      const resourceIds = _.get(data, 'data.jsonContext.resourceList') || []
      this.handleRecord.accountInfo = _.get(data, 'data.jsonContext') || {}
      if (this.type === 'role') {
        // 角色modal
        const resourceList = this.resourceList.map(v => {
          return {
            ...v,
            checked: resourceIds.includes(v.id),
          }
        })
        this.handleRecord.treeData = list2Tree(resourceList)
        this.setState({
          visible: true,
        })
      } else {
        // 账户modal
        this.setState({
          visible: true,
        })
      }
    }
  }

  /**
   * 审核通过
   */
  onOk = () => {
    Modal.confirm({
      content: '确认通过该审批吗？',
      onOk: async() => {
        const { status } = await request().put(checkApi.detail.format({ id: this.handleRecord.id }), {
          status: 'APPROVED',
        })
        if (status === 200) {
          message.success('操作成功')
          this.getList()
          this.handleRecord = {}
          this.setState({
            visible: false,
          })
        }
      },
    })
  }

  /**
   * 审核拒绝
   */
  refuse = () => {
    Modal.confirm({
      content: '确认拒绝该审批吗？',
      onOk: async() => {
        const { status } = await request().put(checkApi.detail.format({ id: this.handleRecord.id }), {
          status: 'REJECTED',
        })
        if (status === 200) {
          message.success('操作成功')
          this.getList()
          this.handleRecord = {}
          this.setState({
            visible: false,
          })
        }
      },
    })
  }

  downloadChaincode = async(path = '') => {
    const fileName = path.split(/[\\\/]/g).slice(-1)[0] || path
    const { status, data } = await request().get(checkApi.downloadChaincode, {
      responseType: 'blob',
      params: {
        approveId: encodeURIComponent(this.handleRecord.id),
      },
    })
    if (status === 200) {
      FileSaver.saveAs(data, fileName)
    }
  }

  renderRoleContent = () => {
    const accountInfo = this.handleRecord.accountInfo || {}
    return <Fragment>
      <Row className="desc-item" gutter={[16, 16]}>
        <Col span={8}>
          <span className="label">角色名称:</span>
          <span className="value" title={accountInfo.name || '--'}>{accountInfo.name || '--'}</span>
        </Col>
        <Col span={16}>
          <span className="label">备注:</span>
          <span className="value" title={accountInfo.desc || '--'}>{accountInfo.desc || '--'}</span>
        </Col>
      </Row>
      {
        this.handleRecord.treeData &&
        <div className="treeData-wrap">
          {
            this.handleRecord.treeData.map(v => {
              return <CheckItem
                key={v.id}
                data={v} />
            })
          }
        </div>
      }
    </Fragment>
  }

  renderAccountContent = () => {
    const accountInfo = this.handleRecord.accountInfo || {}
    return <Row className="desc-item" gutter={[16, 16]}>
      <Col span={8}>
        <span className="label">姓名:</span>
        <span className="value" title={accountInfo.identity_name}>{accountInfo.identity_name}</span>
      </Col>
      <Col span={8}>
        <span className="label">角色:</span>
        <span className="value" title={accountInfo.roleName}>{accountInfo.roleName}</span>
      </Col>
      <Col span={8}>
        <span className="label">登录用户名:</span>
        <span className="value" title={accountInfo.name}>{accountInfo.name}</span>
      </Col>
      <Col span={8}>
        <span className="label">邮箱:</span>
        <span className="value" title={accountInfo.mail_address}>{accountInfo.mail_address}</span>
      </Col>
      <Col span={8}>
        <span className="label">身份证号:</span>
        <span className="value" title={accountInfo.id_card}>{accountInfo.id_card}</span>
      </Col>
      <Col span={8}>
        <span className="label">账户到期时间:</span>
        <span className="value">{accountInfo.expireTime ? moment(accountInfo.expireTime).format('YYYY-MM-DD HH:mm:ss') : '长期有效'}</span>
      </Col>
      <Col span={24}>
        <span className="label">备注:</span>
        <span className="value" title={accountInfo.description}>{accountInfo.description || '--'}</span>
      </Col>
    </Row>
  }

  renderChaincodeContent = () => {
    const accountInfo = this.handleRecord.accountInfo || {}
    return <Row className="desc-item" gutter={[16, 16]}>
      <Col span={8}>
        <span className="label">合约名称:</span>
        <span className="value" title={accountInfo.c_display_name}>{accountInfo.c_display_name}</span>
      </Col>
      <Col span={8}>
        <span className="label">合约标识:</span>
        <span className="value" title={accountInfo.c_name}>{accountInfo.c_name}</span>
      </Col>
      <Col span={8}>
        <span className="label">版本:</span>
        <span className="value" title={accountInfo.c_version}>{accountInfo.c_version}</span>
      </Col>
      <Col span={8}>
        <span className="label">语言:</span>
        <span className="value" title={accountInfo.c_language}>{accountInfo.c_language}</span>
      </Col>
      {
        accountInfo.c_path &&
        <Col span={8}>
          <span className="label"></span>
          <span className="value"><Button type="primary" onClick={() => this.downloadChaincode(accountInfo.c_path)}>下载链码</Button></span>
        </Col>
      }
      <Col span={24}>
        <span className="label">合约描述:</span>
        <span className="value" title={accountInfo.c_description}>{accountInfo.c_description}</span>
      </Col>
    </Row>
  }

  render() {
    const { list, loading, total, visible, modalLoading } = this.state
    return <div className="CheckList">
      <Form ref={c => this.searchForm = c} className="searchForm" layout="inline" onFinish={this.search}>
        <Form.Item label="搜索" name="name">
          <Input style={{ width: '280px' }} placeholder="请输入提交人、被操作对象或者审核人" />
        </Form.Item>
        <Form.Item label="审核类型" name="type">
          <Select style={{ width: '125px' }} placeholder="请选择">
            {
              checkType.map(v => {
                return <Option key={v.value} value={v.value}>{v.label}</Option>
              })
            }
          </Select>
        </Form.Item>
        <Form.Item label="审核状态" name="status">
          <Select style={{ width: '125px' }} placeholder="请选择">
            {
              CheckStatus.map(v => {
                return <Option key={v.value} value={v.value}>{v.label}</Option>
              })
            }
          </Select>
        </Form.Item>
        <Form.Item label="提交时间" name="time">
          <DatePicker.RangePicker />
        </Form.Item>
        <Form.Item className="mb24">
          <Button type="primary" htmlType="submit">
            查询
          </Button>
        </Form.Item>
        <Form.Item className="mb24">
          <Button onClick={this.cancelSearch}>
            重置
          </Button>
        </Form.Item>
      </Form>

      <div style={{ position: 'relative', zIndex: 1 }}>
        <Table
          columns={this.columns}
          className={list.length ? '' : 'empty-list'}
          dataSource={list}
          rowKey="id"
          pagination={false}
          loading={loading}
          onChange={this.onTableChange}
        />
        {
          !list.length &&
          <Empty className="mt24" />
        }
      </div>

      <div className="pagination-box mt24">
        {
          list.length > 0 &&
          <Pagination
            current={this.searchOption.pageNum}
            pageSize={this.searchOption.pageSize}
            total={total}
            showSizeChanger
            onChange={this.onPageChange} />
        }
      </div>

      <Modal
        centered
        destroyOnClose
        className="CheckList-checkModal"
        title={`${this.flag === 'check' ? '审核' : '查看'}`}
        onCancel={() => this.setState({ visible: false })}
        visible={visible}
        width={900}
        maskClosable={false}
        footer={this.flag === 'check' && [
          <Button key="back" onClick={this.refuse}>
            审核拒绝
          </Button>,
          <Button key="submit" type="primary" loading={loading} onClick={this.onOk}>
            审核通过
          </Button>,
        ]}
      >
        <Spin spinning={modalLoading}>
          <Row className="desc-item" gutter={[16, 16]}>
            <Col span={8}>
              <span className="label">审核类型:</span>
              <span className="value">{this.handleRecord.type}</span>
            </Col>
            <Col span={16}>
              <span className="label">提交人:</span>
              <span className="value">{this.handleRecord.applicant_name}</span>
            </Col>
          </Row>
          <Divider plain >提交审核内容</Divider>
          {
            this.type === 'role' && this.renderRoleContent()
          }
          {
            this.type === 'account' && this.renderAccountContent()
          }
          {
            this.type === 'chaincode' && this.renderChaincodeContent()
          }
        </Spin>
      </Modal>
    </div>
  }
}

const CheckStatus = [
  {
    label: '待审核',
    value: 'PENDING_REVIEW',
    color: 'warning',
  },
  {
    label: '已通过',
    value: 'APPROVED',
    color: 'success',
  },
  {
    label: '已拒绝',
    value: 'REJECTED',
    color: 'error',
  },
  {
    label: '处理中',
    value: 'APPROVED_PROCESSING',
    color: 'processing',
  },
]

const checkType = [
  {
    label: '创建角色',
    value: '创建角色',
  },
  {
    label: '修改角色',
    value: '修改角色',
  },
  {
    label: '删除角色',
    value: '删除角色',
  },
  {
    label: '创建账户',
    value: '创建账户',
  },
  {
    label: '修改账户',
    value: '修改账户',
  },
  {
    label: '删除账户',
    value: '删除账户',
  },
]
